<?php
namespace app\controller\api\v1\housing;

use app\Request;
use app\validate\api\housing\HousingHistoricalRecordValidate;
use think\facade\Db;

class HousingHistoricalRecord
{


	public function historicalrecord_add (Request $request)
	{
		[$housing_id] = $request->postMore([['housing_id','']],true);

		$request_data['housing_id'] = $housing_id;
		validate(HousingHistoricalRecordValidate::class)->check($request_data);

		$data['ctime']=date ('Y-m-d H:i:s');
		$data['ttime']=date ('Y-m-d');
		try {
			Db::startTrans();
			$Model = new  \app\model\v1\housing\HousingHistoricalRecord();
			$HousingHistoricalRecord=$Model->where ('housing_id',$request_data['housing_id'])
					->where ('user_id',$request->uid())
					->find ();
			$HousingHistoricalRecord_count=$Model->where ('user_id',$request->uid())
				->count ();
			if ($HousingHistoricalRecord&&$HousingHistoricalRecord_count<=100){
				$Model->where ('housing_id',$request_data['housing_id'])
					->where ('user_id',$request->uid())->update ($data);
			}else{
				$data['housing_id'] =$request_data['housing_id'];
				$data['user_id']=$request->uid();
				$Model->insert ($data);
			}
			Db::commit();
		} catch (\Exception $e) {
			Db::rollback();
			$results['msg'] = $e->getMessage();
			return  app('json')->fail($results['msg']);

		}
		return  app('json')->status('success','成功');
	}

	public function historicalrecord_list (Request $request)
	{
		[$type,$page,$limit]=$request->postMore([
			['type', ''],
			['page', 1],
			['limit', 30]
		], true);

		try {
			Db::startTrans();
			$Model = new  \app\model\v1\housing\HousingSource();
			$data = $Model->alias ('a')
				->with ('HousingHousingLabelAssociation')
				->join('housing_historical_record r','r.housing_id = a.id')
				->where(function ($a) use ($type) {
					if (!empty($type)){
						$a -> where ('a.housing_type', $type);

					}
				})
				->where ('r.user_id',$request->uid())
				->page ($page,$limit)
				->order ('ctime','desc')
				->field ('a.id,a.housing_source_door_head_img,a.architecture_area,a.architecture_rent,a.housing_source_title,a.type,a.is_proprietor,a.status,a.shop_type,r.ttime,housing_type,address')
				->select();
			$area_list ['count']= $Model->alias ('a')
				->join('housing_historical_record r','r.housing_id = a.id')
				->where ('a.type',$type)
				->where ('r.user_id',$request->uid())
				->count();
			$area_list = [];

			foreach ($data as $key => $value) {
				$area_list['data'][$value['ttime']][] = $value;
			}
			Db::commit();
		} catch (\Exception $e) {
			Db::rollback();
			$results['msg'] = $e->getMessage();
			return  app('json')->fail($results['msg']);
		}
		return  app('json')->status('success','成功',$area_list);


	}


}
